<template>
  <div class="record-manage">
    <!-- 页面标题与操作区 -->
    <div class="header">
      <h2>记录查询</h2>
      <el-button type="primary" @click="handleExport" :loading="exportLoading">
        <el-icon><Download /></el-icon> 导出记录
      </el-button>
    </div>

    <!-- 筛选条件区域 -->
    <div class="filter-panel">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="用户姓名" class="filter-item">
            <el-input v-model="filters.name" placeholder="请输入用户姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机号" class="filter-item">
            <el-input v-model="filters.phone" placeholder="请输入手机号" maxlength="11" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="门禁地点" class="filter-item">
            <el-select v-model="filters.location" placeholder="请选择门禁地点">
              <el-option label="小区正门" value="main_gate" />
              <el-option label="1号楼单元门" value="building1" />
              <el-option label="2号楼单元门" value="building2" />
              <el-option label="地下车库入口" value="garage" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="操作类型" class="filter-item">
            <el-select v-model="filters.type" placeholder="请选择操作类型">
              <el-option label="进门" value="enter" />
              <el-option label="出门" value="exit" />
              <el-option label="异常尝试" value="abnormal" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 15px">
        <el-col :span="12">
          <el-form-item label="时间范围" class="filter-item">
            <el-date-picker
              v-model="filters.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="filter-actions">
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stats-container">
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-label">总记录</div>
          <div class="stat-value">{{ todayTotal }}</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-label">异常记录</div>
          <div class="stat-value text-warning">{{ abnormalTotal }}</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-label">园内人数记录</div>
          <div class="stat-value text-success">{{ onlineTotal }}</div>
        </div>
      </el-card>
    </div>

    <!-- 记录表格 -->
    <el-table
      :data="filteredRecords"
      stripe
      border
      v-loading="tableLoading"
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="id" label="序号" width="80" />
      <el-table-column prop="userName" label="用户姓名" />
      <el-table-column prop="userPhone" label="手机号" />
      <el-table-column prop="location" label="门禁地点">
        <template #default="scope">
          {{ formatLocation(scope.row.location) }}
        </template>
      </el-table-column>
      <el-table-column prop="type" label="操作类型">
        <template #default="scope">
          <el-tag :type="getTypeTagType(scope.row.type)">
            {{ formatType(scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="time" label="操作时间" />
      <el-table-column prop="method" label="验证方式" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button size="small" @click="handleViewDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination" v-if="total > 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="记录详情"
      :width="500"
      :before-close="handleCloseDetail"
    >
      <div class="detail-info" v-if="currentRecord">
        <div class="detail-item">
          <span class="detail-label">记录ID：</span>
          <span class="detail-value">{{ currentRecord.id }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">用户姓名：</span>
          <span class="detail-value">{{ currentRecord.userName }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">手机号：</span>
          <span class="detail-value">{{ currentRecord.userPhone }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">业主姓名：</span>
          <span class="detail-value">{{ currentRecord.ownerName }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">楼栋房间：</span>
          <span class="detail-value">{{ currentRecord.roomNumber }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">门禁地点：</span>
          <span class="detail-value">{{ formatLocation(currentRecord.location) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">操作类型：</span>
          <span class="detail-value">
            <el-tag :type="getTypeTagType(currentRecord.type)">
              {{ formatType(currentRecord.type) }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="detail-label">验证方式：</span>
          <span class="detail-value">{{ currentRecord.method }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">操作时间：</span>
          <span class="detail-value">{{ currentRecord.time }}</span>
        </div>
        <div class="detail-item" v-if="currentRecord.type === 'abnormal'">
          <span class="detail-label">异常原因：</span>
          <span class="detail-value text-warning">{{ currentRecord.reason }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">设备编号：</span>
          <span class="detail-value">{{ currentRecord.deviceId }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 定义记录数据类型
interface AccessRecord {
  id: number
  userName: string
  userPhone: string
  ownerName: string
  roomNumber: string
  location: 'main_gate' | 'building1' | 'building2' | 'garage'
  type: 'enter' | 'exit' | 'abnormal'
  method: string
  time: string
  deviceId: string
  reason?: string // 异常原因，仅异常记录有
}

// 筛选条件
const filters = ref({
  name: '',
  phone: '',
  location: '',
  type: '',
  timeRange: [] as string[],
})

// 表格状态
const tableLoading = ref(false)
const exportLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const records = ref<AccessRecord[]>([])
const filteredRecords = ref<AccessRecord[]>([])

// 统计数据
const todayTotal = ref(0)
const abnormalTotal = ref(0)
const onlineTotal = ref(0)

// 详情弹窗
const detailVisible = ref(false)
const currentRecord = ref<AccessRecord | null>(null)

// 模拟记录数据
const generateMockData = (): AccessRecord[] => {
  const locations = ['main_gate', 'building1', 'building2', 'garage'] as const
  const types = ['enter', 'exit', 'abnormal'] as const
  const methods = ['人脸识别', '刷卡', '密码', '手机APP']

  const mockData: AccessRecord[] = []
  for (let i = 1; i <= 56; i++) {
    const type = types[Math.floor(Math.random() * types.length)]
    const now = new Date()
    now.setMinutes(now.getMinutes() - Math.floor(Math.random() * 1440)) // 随机1天内的时间

    mockData.push({
      id: i,
      userName: `用户${i}`,
      userPhone: `13${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 100000000)}`,
      ownerName: i % 5 === 0 ? `业主${Math.floor(i / 5)}` : `用户${i}`,
      roomNumber: `${Math.floor(Math.random() * 3) + 1}号楼${Math.floor(Math.random() * 30) + 101}`,
      location: locations[Math.floor(Math.random() * locations.length)],
      type,
      method: methods[Math.floor(Math.random() * methods.length)],
      time: now.toISOString().slice(0, 19).replace('T', ' '),
      deviceId: `DEV-${Math.floor(Math.random() * 1000)
        .toString()
        .padStart(3, '0')}`,
      ...(type === 'abnormal' && {
        reason: ['权限不足', '验证失败', '设备异常', '多次尝试'][Math.floor(Math.random() * 4)],
      }),
    })
  }
  return mockData
}

// 格式化地点显示
const formatLocation = (location: string) => {
  const locationMap: Record<string, string> = {
    main_gate: '小区正门',
    building1: '1号楼单元门',
    building2: '2号楼单元门',
    garage: '地下车库入口',
  }
  return locationMap[location] || location
}

// 格式化操作类型显示
const formatType = (type: string) => {
  const typeMap: Record<string, string> = {
    enter: '进门',
    exit: '出门',
    abnormal: '异常尝试',
  }
  return typeMap[type] || type
}

// 获取操作类型标签样式
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    enter: 'success',
    exit: 'info',
    abnormal: 'warning',
  }
  return typeMap[type] || 'default'
}

// 处理查询
const handleQuery = () => {
  tableLoading.value = true
  setTimeout(() => {
    // 筛选逻辑
    let result = [...records.value]

    if (filters.value.name) {
      result = result.filter((item) => item.userName.includes(filters.value.name))
    }

    if (filters.value.phone) {
      result = result.filter((item) => item.userPhone.includes(filters.value.phone))
    }

    if (filters.value.location) {
      result = result.filter((item) => item.location === filters.value.location)
    }

    if (filters.value.type) {
      result = result.filter((item) => item.type === filters.value.type)
    }

    if (filters.value.timeRange && filters.value.timeRange.length === 2) {
      const [start, end] = filters.value.timeRange
      result = result.filter((item) => item.time >= start && item.time <= end)
    }

    // 更新表格数据
    total.value = result.length
    filteredRecords.value = result.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value,
    )

    tableLoading.value = false
  }, 500)
}

// 重置筛选条件
const handleReset = () => {
  filters.value = {
    name: '',
    phone: '',
    location: '',
    type: '',
    timeRange: [],
  }
  currentPage.value = 1
  handleQuery()
}

// 分页大小变更
const handleSizeChange = (val: number) => {
  pageSize.value = val
  handleQuery()
}

// 页码变更
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  handleQuery()
}

// 查看详情
const handleViewDetail = (record: AccessRecord) => {
  currentRecord.value = record
  detailVisible.value = true
}

// 关闭详情弹窗
const handleCloseDetail = () => {
  detailVisible.value = false
  currentRecord.value = null
}

// 导出记录
const handleExport = () => {
  exportLoading.value = true
  // 模拟导出操作
  setTimeout(() => {
    exportLoading.value = false
    ElMessage.success('记录导出成功')
  }, 1500)
}

// 页面加载时初始化数据
onMounted(() => {
  records.value = generateMockData()

  // 计算统计数据
  const today = new Date().toISOString().slice(0, 10)
  todayTotal.value = records.value.filter((item) => item.time.startsWith(today)).length

  abnormalTotal.value = records.value.filter((item) => item.type === 'abnormal').length

  // 模拟在线人数
  onlineTotal.value = Math.floor(Math.random() * 30) + 5

  // 初始查询
  handleQuery()
})
</script>

<style scoped lang="scss">
.record-manage {
  padding: 24px;
  background: #fafafa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-panel {
  background: #fff;
  padding: 20px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 20px;
}

::v-deep .filter-item {
  width: 100%;
}

::v-deep .el-form-item {
  margin-bottom: 0;
}

.filter-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.stats-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  min-width: 150px;
}

.stat-item {
  text-align: center;
  padding: 15px 0;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  display: block;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.detail-info {
  margin-top: 10px;
}

.detail-item {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.detail-label {
  width: 100px;
  color: #666;
  font-size: 14px;
}

.detail-value {
  flex: 1;
  font-size: 14px;
}

.text-warning {
  color: #faad14;
}

.text-success {
  color: #52c41a;
}

// 响应式调整
@media (max-width: 1200px) {
  .stats-container {
    flex-wrap: wrap;
  }

  .stat-card {
    flex: 1 1 calc(50% - 10px);
  }
}

@media (max-width: 768px) {
  .stats-container {
    flex-direction: column;
  }

  .filter-actions {
    justify-content: flex-start;
    margin-top: 10px;
  }
}
</style>
